import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    token: localStorage.getItem('token') || '',
    cartList: JSON.parse(localStorage.getItem('cartList') || '[]')
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    RESET_USER(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    ADD_TO_CART(state, { dish, count, restaurantId, restaurantName }) {
      let cartList = state.cartList
      let found = false
      
      // 检查是否已存在来自不同餐厅的菜品
      const existingRestaurantId = cartList.length > 0 ? cartList[0].restaurantId : null
      if (existingRestaurantId && existingRestaurantId !== restaurantId) {
        cartList = [] // 清空购物车
      }
      
      for (let item of cartList) {
        if (item.dish.id === dish.id) {
          item.count += count
          found = true
          break
        }
      }
      
      if (!found) {
        cartList.push({
          dish,
          count,
          restaurantId,
          restaurantName
        })
      }
      
      state.cartList = cartList
      localStorage.setItem('cartList', JSON.stringify(cartList))
    },
    UPDATE_CART_ITEM(state, { dishId, count }) {
      const cartList = state.cartList
      for (let item of cartList) {
        if (item.dish.id === dishId) {
          item.count = count
          break
        }
      }
      state.cartList = cartList
      localStorage.setItem('cartList', JSON.stringify(cartList))
    },
    REMOVE_FROM_CART(state, dishId) {
      const cartList = state.cartList.filter(item => item.dish.id !== dishId)
      state.cartList = cartList
      localStorage.setItem('cartList', JSON.stringify(cartList))
    },
    CLEAR_CART(state) {
      state.cartList = []
      localStorage.removeItem('cartList')
    }
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$http.post('/user/login', userInfo)
          .then(response => {
            const { data } = response.data
            commit('SET_TOKEN', data.token)
            commit('SET_USER_INFO', data.userInfo)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    register({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$http.post('/user/register', userInfo)
          .then(response => {
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    logout({ commit }) {
      commit('RESET_USER')
      commit('CLEAR_CART')
    },
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        Vue.prototype.$http.get('/user/info')
          .then(response => {
            const { data } = response.data
            commit('SET_USER_INFO', data)
            resolve(data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    resetToken({ commit }) {
      commit('RESET_USER')
    }
  },
  getters: {
    isLoggedIn: state => !!state.token,
    isAdmin: state => state.userInfo.role === 'admin',
    cartCount: state => {
      return state.cartList.reduce((total, item) => total + item.count, 0)
    },
    cartTotal: state => {
      return state.cartList.reduce((total, item) => total + item.dish.price * item.count, 0)
    }
  }
})

